<template>
  <el-dialog
    v-model="visibility"
    :title="props.sonRowData.name ? config.button.text.edit : config.button.text.add"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="仓储费名称"
            prop="name">
            <el-input
              v-model="formData.name"
              placeholder="仓储费名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="仓储费(元/吨)"
            prop="storageChargeFee">
            <el-input-number
              style="width: 100%;"
              v-model="formData.storageChargeFee"
              :min="0"
              :max="100"
              placeholder="仓储费(元/吨)" />
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="是否按照时间段"
            prop="isTimeSection">
            <el-select
              v-model="formData.isTimeSection"
              placeholder="是否按照时间段"
              clearable>
              <el-option
                :label="config.button.text.yes"
                :value="true" />
              <el-option
                :label="config.button.text.no"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          v-if="formData.isTimeSection"
          :span="12"
          class="el_col_fit"
          style="margin-bottom: 5px;text-align: right;">
          <el-button
            type="info"
            @click="addTimeDuring">
            <template #icon>
              <el-icon>
                <CirclePlus />
              </el-icon>
            </template>
            新增时间段
          </el-button>
        </el-col>
      </el-row>
      <el-table
        v-if="formData.isTimeSection&&!appStore.isPhone"
        max-height="300px"
        :data="sectionRuleList"
        style="width: 100%"
        border="1">
        <el-table-column
          prop="startDay"
          label="开始天数"
          min-width="100"
          :resizable="false">
          <template #default="scope">
            <span v-show="scope.$index !== editIndex||scope.$index===0">{{ scope.row.startDay || 0}}</span>
            <el-input-number
              :min="0"
              controls-position="right"
              v-show="scope.$index === editIndex&&scope.$index!==0"
              v-model="scope.row.startDay"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="endDay"
          label="结束天数"
          min-width="100"
          :resizable="false">
          <template #default="scope">
            <span v-show="scope.$index !== editIndex">{{ scope.row.endDay }}</span>
            <el-input-number
              :min="0"
              v-show="scope.$index === editIndex"
              v-model="scope.row.endDay"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="ratio"
          label="比率"
          min-width="100"
          :resizable="false">
          <template #default="scope">
            <span v-show="scope.$index !== editIndex">{{ scope.row.ratio }}</span>
            <el-input-number
              :min="0"
              v-show="scope.$index === editIndex"
              v-model="scope.row.ratio"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="200"
          :resizable="false">
          <template #default="{ row, index }">
            <el-button
              type="warning"
              @click="handleEdit(row)">
              {{ config.button.text.edit }}
            </el-button>
            <el-button
              type="warning"
              @click="handleDelete(index)">
              {{ config.button.text.delete }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-card
        v-if="formData.isTimeSection&&appStore.isPhone"
        class="table_card info-card"
        v-for="(item,index) in sectionRuleList"
        :key="item.id"
        @click="editTimeSlot(item,index)">
        <div class="info-item">
          <div class="info-title">开始天数：</div>
          <div class="info-main">{{ item.startDay }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">结束天数：</div>
          <div class="info-main">{{ item.endDay }}</div>
        </div>
        <div class="info-item">
          <div class="info-title">比率：</div>
          <div class="info-main">{{ item.ratio }}</div>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          v-if="props.quoteInfo && props.quoteInfo.isQuote"
          @click="quoteEvent">
          {{ config.button.text.quote }}
        </el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <Edit
    ref="timeSlotRef"
    :timeSlotRowData="timeSlotRowData"
    @confirm="getTimeSlot" />

  <Quote
    v-if="props.quoteInfo"
    ref="quoteRef"
    @selected="selected"
    :baseCapitalWarehouseId="props.quoteInfo.baseCapitalWarehouseId" />
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import ApiBaseCapitalWarehouse from "@/api/modules/capital-ware-house"
import { useValidator } from "@/hooks/useValidator";
import Quote from "@/views/purchase-order-insert/component/Quote.vue";
import { useAppStore } from "@/stores/app"
import Edit from "./timeSlotEdit.vue"

const appStore = useAppStore()

const visibility = ref(false)
const formData = ref({})
const formRef = ref()
const quoteRef = ref()
const timeSlotRowData = ref({})
const timeSlotRef = ref()
const { required, validate, clearValidate } = useValidator()

const formRules = {
  name: [required("仓储费名称")],
  storageChargeFee: [required("仓储费（元/吨）")],
  isTimeSection: [required("是否按照时间段", "change")],
  beginDays: [required("开始天数")],
  endDays: [required("结束天数")],
  ratio: [required("比率")]
}

const props = defineProps(["sonRowData", "quoteInfo"])

const emits = defineEmits(["sonSave"])

const sectionRuleList = ref([]);

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    formData.value = props.sonRowData
    editIndex.value = -1
    if (formData.value.sectionRuleJson) {
      sectionRuleList.value = JSON.parse(formData.value.sectionRuleJson);
    } else {
      sectionRuleList.value = []
    }
    setTimeout(() => {
      clearValidate(formRef.value)
    })
  }
}, { immediate: true })

const editIndex = ref(-1)

const editTimeSlot = (rowData,index) => {
  timeSlotRef.value.visibility = true;
  timeSlotRowData.value = {...rowData,index:index};
}

const getTimeSlot = (info) => {
  let rowInfo = {...info};
  delete rowInfo.index;
  sectionRuleList.value[info.index] = rowInfo;
  timeSlotRef.value.visibility = false;
}

const handleEdit = (row) => {
  editIndex.value = sectionRuleList.value.indexOf(row)
}

const quoteEvent = () => {
  quoteRef.value.visibility = true
}
const selected = (data) => {
  formData.value.isTimeSection = data.isTimeSection
  formData.value.name = data.name
  formData.value.sectionRuleJson = data.sectionRuleJson
  formData.value.storageChargeFee = data.storageChargeFee
  sectionRuleList.value = JSON.parse(formData.value.sectionRuleJson)
  quoteRef.value.visibility = false
}

const saveEvent = async () => {
  await validate(formRef.value)
  formData.value.sectionRuleJson = JSON.stringify(sectionRuleList.value);
  //判断是否为最外层新增
  if (formData.value?.baseCapitalWarehouseId) {
    //判断是否为仓储费新增还是修改
    if (formData.value?.id) {
      await ApiBaseCapitalWarehouse.changeStorageChargeList(formData.value)
    } else {
      await ApiBaseCapitalWarehouse.addStorageChargeList([formData.value])
    }
    emits("sonSave", null)
  } else {
    //处理最外层新增情况
    //当为新增的时候
    emits("sonSave", formData.value)
  }
}

const handleDelete = (index) => {
  sectionRuleList.value.splice(index, 1);
}

//新增时间段
const addTimeDuring = () => {
  const addObj = { startDay: "0", endDay: "0", ratio: "0" }
  sectionRuleList.value.push(addObj)
  editIndex.value = sectionRuleList.value.indexOf(addObj)
}

defineExpose({ visibility })
</script>

<style lang="scss" scoped>
:deep(.el-form-item label) {
  width: 140px !important;
}
.info-card {
  // padding: 10px;
  margin-bottom: 3px;
  .info-item {
    display: flex;
    padding: 5px 0;
    align-items: end;
    .info-title{
      width: 120px;
      color: #999;
    }
    .info-main{
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
:deep(.el-table .cell){
  text-overflow:unset;
}
:deep(.el-input-number){
  width: auto !important;
}
</style>
